package com.threeox.ormlibrary.db;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;

import com.threeox.ormlibrary.DBApplcation;
import com.threeox.ormlibrary.R;
import com.threeox.ormlibrary.util.TableUtil;
import com.threeox.utillibrary.util.LogUtils;

/**
 *
 * @ClassName: SuperDatabaseManager
 *
 * @Description: (基本的数据库管理类   初始化创建基库)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2016/12/16 15:52 
 * 
 * @version 1.0
 */
public class OrmDatabaseManager extends SQLiteOpenHelper {

	private Context mContext = null;
	private String[] mDBPackNames = null;
	public static OrmDatabaseManager mDatabaseManager = null;

	private OrmDatabaseManager(Context context, Bundle metaData) {
		super(context, metaData.getString(context.getString(R.string.db_name)), null, metaData.getInt(context.getString(R.string.db_version)));
		this.mContext = context;
		this.mDBPackNames = metaData.getString(context.getString(R.string.db_packnames)).split(";");
	}

	public static OrmDatabaseManager getInstance() {
		if (mDatabaseManager == null) {
			synchronized (OrmDatabaseManager.class) {
				if (mDatabaseManager == null) {
					try {
						DBApplcation applcation = DBApplcation.getInstance();
						ApplicationInfo appInfo = applcation.getPackageManager().
								getApplicationInfo(applcation.getPackageName(), PackageManager.GET_META_DATA);
						Bundle metaData = appInfo.metaData;
						if (metaData != null)
							mDatabaseManager = new OrmDatabaseManager(applcation, metaData);
						else
							LogUtils.e("创建数据库请配置参数!");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return mDatabaseManager;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			TableUtil.getInstance(mContext, db, mDBPackNames).createTable();
		} catch (Exception e) {
			LogUtils.e(this.getClass(), "新增数据库失败:" + e.getMessage());
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		try {
			TableUtil.getInstance(mContext, db, mDBPackNames).createTable().alterTable(oldVersion);
		} catch (Exception e) {
			LogUtils.e(this.getClass(), "更新数据库失败:" + e.getMessage());
		}
	}
}
